package com.ljm.sys.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljm.common.enums.DataStatus;
import com.ljm.common.enums.ResultStatus;
import com.ljm.common.excuption.Assert;
import com.ljm.common.page.PageDto;
import com.ljm.common.util.BeanUtils;
import com.ljm.common.util.PageUtil;
import com.ljm.common.util.StringUtil;
import com.ljm.pass.util.PasswordHelper;
import com.ljm.sys.auth.service.ISysAuthUserRoleService;
import com.ljm.sys.org.api.SysOrgUserApi;
import com.ljm.sys.org.dto.SysOrgUserDto;
import com.ljm.sys.org.entity.SysOrgUser;
import com.ljm.sys.org.mapper.SysOrgUserMapper;
import com.ljm.sys.org.service.ISysOrgUserDepartService;
import com.ljm.sys.org.service.ISysOrgUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author HuamingChen
 * @since 2018-12-19
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class SysOrgUserServiceImpl extends ServiceImpl<SysOrgUserMapper, SysOrgUser>
        implements ISysOrgUserService, SysOrgUserApi {

    /**
     * 密码工具类
     */
    @Resource
    private PasswordHelper passwordHelper;
    /**
     * 角色接口
     */
    @Resource
    private ISysAuthUserRoleService sysAuthUserRoleService;
    /**
     * 用户数据接口
     */
    @Resource
    private SysOrgUserMapper sysOrgUserMapper;

    /**
     * 部门关联接口
     */
    @Resource
    private ISysOrgUserDepartService sysOrgUserDepartService;

    @Override
    public SysOrgUserDto getUserByUserName(String userName){
        if (StringUtil.isEmpty(userName)) {
            Assert.throwException(ResultStatus.FIAL.getCode(), "请输入用户帐号");
        }
        QueryWrapper<SysOrgUser> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", userName);
        SysOrgUser user = this.getOne(wrapper);
        SysOrgUserDto dto = new SysOrgUserDto();
        if (!StringUtil.isEmpty(user)) {
            BeanUtils.copyProperties(user, dto);
        }
        return dto;
    }

    @Override
    public List<SysOrgUserDto> getAllUser(){
        List<SysOrgUserDto> list=new ArrayList<>();
        QueryWrapper<SysOrgUser> wrapper=new QueryWrapper<>();
        List<SysOrgUser> pos=this.list(wrapper);
        if(!StringUtil.isEmpty(pos)){
            pos.forEach(po->{
                SysOrgUserDto dto=new SysOrgUserDto();
                po.setSalt(null);
                po.setLoginPwd(null);
                BeanUtils.copyProperties(po,dto);
                list.add(dto);
            });
        }
        return list;
    }

    @Override
    public void saveData(SysOrgUserDto dto, SysOrgUserDto curUser) {
        SysOrgUser po=new SysOrgUser();
        BeanUtils.copyProperties(dto,po);
        if(StringUtil.isEmpty(dto.getId())){
            //校验用户是否存在
            if(this.checkIsExict(po.getLoginName())){
                Assert.throwException(ResultStatus.FIAL.getCode(),"该用户已经存在");
            }
            po.setCreateTime(LocalDateTime.now());
            po.setCreater(curUser.getLoginName());
            po.setStatus(DataStatus.NORMAL.getCode());
            po.setOrgId(curUser.getOrgId());
            //生成密文密码
            // 1 生成salt
            po.setSalt(StringUtil.get32UUID());
            // 2 生成密码
            po.setLoginPwd(passwordHelper.getPwd(dto.getLoginPwd(),po.getSalt()));
        }
        po.setEditor(curUser.getLoginName());
        po.setEditTime(LocalDateTime.now());

        this.saveOrUpdate(po);
        //保存部门信息
        sysOrgUserDepartService.userRefDept(dto.getDeptIds(),po.getId(),curUser);
        //保存角色信息
        sysAuthUserRoleService.userRefRole(new ArrayList<>(dto.getRoles()),po.getId(),curUser);
    }

    /**
     * 校验用户是否存在
     * @param loginName 账号
     * @return 是否存在结果
     */
    private boolean checkIsExict(String loginName){
        boolean result=false;
        QueryWrapper<SysOrgUser> wrapper= new QueryWrapper<>();
        wrapper.eq("login_name",loginName);
        if(this.count(wrapper)>0){
            result=true;
        }
        return result;
    }

    @Override
    public void delData(List<Long> ids) {
        if(StringUtil.isEmpty(ids)){
            Assert.throwException(ResultStatus.FIAL.getCode(),"请选择要删除的列");
        }
        this.removeByIds(ids);
    }

    @Override
    public SysOrgUserDto getDataById(Long id) {
        if(StringUtil.isEmpty(id)){
            Assert.throwException(ResultStatus.FIAL.getCode(),"主键为空");
        }
        SysOrgUserDto dto=new SysOrgUserDto();
        SysOrgUser po=this.getById(id);
        BeanUtils.copyProperties(po,dto);
        dto.setSalt(null);
        dto.setLoginPwd(null);
        //查询部门信息
        dto.setDeptIds(sysOrgUserDepartService.getRefDeptByUserId(dto.getId()));
        //查询角色信息
        dto.setRoles(sysAuthUserRoleService.getDataByUserId(dto.getId()));
        return dto;
    }

    @Override
    public PageDto<SysOrgUserDto> getDataByPage(String fullName,String loginName, String realName, String identityNo, String email, Integer pageNo, Integer pageSize) {
        PageDto<SysOrgUserDto> pageDto=new PageDto<>(pageNo,pageSize);
        Integer total=sysOrgUserMapper.countRow(fullName,loginName,realName,identityNo,email);
        if(total>0){
            List<SysOrgUser> pos=sysOrgUserMapper.getPageRecord(fullName,loginName,realName,identityNo,email, PageUtil.getStartRow(pageNo,pageSize),pageSize);
            if(!StringUtil.isEmpty(pos)){
                pageDto.setRecords(BeanUtils.copyPropertiesByList(pos,SysOrgUserDto.class));
                pageDto.setTotal(total);
            }
        }
        return pageDto;
    }
}
